package edu.zjut.hjg.saas.web.controller.admin;

import static edu.zjut.hjg.saas.web.support.SaaSConstants.SESSION_NAME_ADMIN;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import edu.zjut.hjg.saas.biz.service.AdminService;
import edu.zjut.hjg.saas.biz.service.exception.ServiceException;
import edu.zjut.hjg.saas.common.annotation.CookieSessionIn;
import edu.zjut.hjg.saas.common.util.ParameterUtil;
import edu.zjut.hjg.saas.web.model.AdminSession;

@Controller
@RequestMapping("/admin/password")
public class PasswordController {

    private static final Log log = LogFactory.getLog(PasswordController.class);

    @Autowired
    private AdminService     adminService;

    @RequestMapping(value = "/update.htm", method = RequestMethod.POST)
    @CookieSessionIn(value = SESSION_NAME_ADMIN, param = "session")
    public String update(String oldPassword, String newPassword, AdminSession session, Model model) {
        if (!ParameterUtil.notBlank(oldPassword, newPassword)) {
            return "admin/password/index";
        }
        try {
            adminService.updatePassword(session.getId(), oldPassword, newPassword);
        } catch (ServiceException e) {
            log.warn(e.getMessage() + "," + e.getErrorMessage(), e);
            model.addAttribute("errorMsg", e.getErrorMessage());
            return "admin/password/index";
        }
        model.addAttribute("msgCode", "message.updatePassword.success");
        return "admin/password/index";
    }
}
